(function () {
    var $ = null;

    var HUTYPE_LIUJU = 0;
    var HUTYPE_ZIMO = 1;
    var HUTYPE_DIANPAO = 2;

    majiang.JiesuanLayer = cc.Layer.extend({
        onEnter: function () {
            cc.Layer.prototype.onEnter.call(this);
        },
        onExit: function () {
            cc.Layer.prototype.onExit.call(this);
            network.start();
        },
        ctor: function (data) {
            this._super();
            var that = this;
            loadNodeCCS(majiang.res.JiesuanLayer_json, this);
            $ = create$(this.getChildByName('Scene'));

            var mapId = data['map_id'];
            var isZimo = (data['hu_type'] == HUTYPE_ZIMO);
            var isLiuju = (data['hu_type'] == HUTYPE_LIUJU);
            var isDianpao = (data['hu_type'] == HUTYPE_DIANPAO);
            var zhuangUid = data['zhuang'];
            var dianpaoUid = data['dianpao_uid'];
            var huPaiId = data['hu_pai_id'];
            var title = (data['map_name'] || gameData.mapName || (data['map_id'] ? (gameData.mapId2Name[mapId]) || '' : ''));
            if (data['map_name'].indexOf('麻将') < 0) {
                title = decodeURIComponent(data['map_name'] + '-');
            }

            //playEffect('vLiuju');

            var players = data.players;

            var hupaiMap = data['hu_pai_map'];
            if (hupaiMap) {
                for (uid in hupaiMap)
                    if (hupaiMap[uid] && hupaiMap[uid].length > 0)
                        huPaiId = 1;
            }
            else {
                hupaiMap = {};
                for (var i = 0; i < players.length; i++) {
                    var player = players[i];
                    hupaiMap[player.uid] = [huPaiId];
                }
            }
            // if (false) ;
            // else if (isLiuju) title += '流局';
            // else if (isZimo) title += '自摸';
            // else if (isDianpao) title += '点炮';
            // else title += '解散';
            if (isLiuju) {
                $('root.panel.word_liuju').setVisible(true);
                $('root.panel.word_shibai').setVisible(false);
                $('root.panel.word_shengli').setVisible(false);
            }

            var title = data['title'] || title;

            var btnFenxiang = $('root.panel.btn_fenxiang');
            var btnStart = $('root.panel.btn_start');
            var btnChakan = $('root.panel.btn_chakan');

            if (gameData.loginType == 'yk') {
                btnFenxiang.setVisible(false);
                //btnStart.setPositionX(btnStart.getParent().getContentSize().width / 2);
            }
            if (window.inReview) {
                btnFenxiang.setVisible(false);
            }

            var huCnt = 0;
            var diangangMap = {};
            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var isHu = player['hu'];
                if (isHu) {
                    huCnt += 1;
                }

                var duiArr = player['dui_arr'];
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                    if (dui['from_uid'] && dui['from_uid'] != player.uid) {
                        diangangMap[dui['from_uid']] = diangangMap[dui['from_uid']] || 0;
                        diangangMap[dui['from_uid']]++;
                    }
                }
            }

            for (var i = 0; i < players.length; i++) {
                var player = players[i];
                var uid = player['uid'];
                var score = player['score'];
                var gangScore = player['gang_score'];
                var fan = player['fan'];
                var paiArr = player['pai_arr'];
                var duiArr = player['dui_arr'];
                var textArr = player['text_arr'];
                var isHu = player['hu'];
                var extra_score = player['extra_score'] || 0;

                var paiIdArr = [];

                if (!$('root.panel.row' + i))
                    continue;

                if (!title && uid == gameData.uid)
                    title = (isHu ? '胡牌' : '失败');
                if (isHu) {
                    var showselfY = $('root.panel.row' + i).getPositionY();
                    //$('root.panel.jianbian_bg').setPositionY(showselfY);
                }
                if (!isLiuju && uid == gameData.uid) {
                    $('root.panel.word_shengli').setVisible(isHu);
                    $('root.panel.word_shibai').setVisible(!isHu);
                    $('root.panel.word_liuju').setVisible(false);
                }

                if (isHu) {
                    var idx = paiArr.indexOf(huPaiId);
                    if (idx >= 0) {
                        paiArr.splice(idx, 1);
                    }
                }

                var gouchengArr = [];

                var playerInfo = gameData.getPlayerInfoByUid(uid);
                $('root.panel.row' + i + '.lb_zhuang').setVisible(zhuangUid == uid ? true : false);
                $('root.panel.row' + i + '.lb_nickname').setString(playerInfo.nickname);

                $('root.panel.row' + i + '.hu').setVisible(isHu);

                var piaoNode;
                if (extra_score < 0) {
                    safeHide($('root.panel.row' + i + '.lb_piao'));
                    piaoNode = $('root.panel.row' + i + '.lb_piao_minus');
                    safeShow(piaoNode);
                }
                else {
                    safeHide($('root.panel.row' + i + '.lb_piao_minus'));
                    piaoNode = $('root.panel.row' + i + '.lb_piao');
                    safeShow(piaoNode);
                }
                if (extra_score !== 0) {
                    safeShow($('root.panel.row' + i + '.lb_piao_text'));
                    safeShow(piaoNode);
                } else {
                    safeHide(piaoNode);
                    safeHide($('root.panel.row' + i + '.lb_piao_text'));
                }
                safeString(piaoNode, extra_score);
                /*
                if (fan < 0) {
                    $('root.panel.row' + i + '.lb_score').setFntFile('res/fonts/jianfemblue.fnt');
                }
                $('root.panel.row' + i + '.lb_score').setString(fan.toString());
                 */
                var gangNode;
                if (gangScore < 0) {
                    gangNode = $('root.panel.row' + i + '.lb_score_gang_minus');
                    safeShow(gangNode);
                    safeHide($('root.panel.row' + i + '.lb_score_gang'));
                }
                else {
                    gangNode = $('root.panel.row' + i + '.lb_score_gang');
                    safeShow(gangNode);
                    safeHide($('root.panel.row' + i + '.lb_score_gang_minus'));
                }
                gangNode.setString(gangScore.toString());

                if (gameData.mapId == MAP_ID_WUHAN_KAIKOU || gameData.mapId == MAP_ID_WUHAN_KOUKOU) {
                    $('root.panel.row' + i + '.lb_score_gang').setVisible(false);
                    $('root.panel.row' + i + '.lb_score_gang_minus').setVisible(false);
                    $('root.panel.row' + i + '.lb_gangCnt').setVisible(false);
                }

                var scoreSumNode;
                if (score < 0) {
                    scoreSumNode = $('root.panel.row' + i + '.lb_score_sum_minus');
                    safeShow(scoreSumNode);
                    safeHide($('root.panel.row' + i + '.lb_score_sum'));
                }
                else {
                    scoreSumNode = $('root.panel.row' + i + '.lb_score_sum');
                    safeShow(scoreSumNode);
                    safeHide($('root.panel.row' + i + '.lb_score_sum_minus'));
                }
                scoreSumNode.setString(score < 0 ? score : ('+' + score.toString()));

                while (true) {
                    for (var j = 0; j < duiArr.length; j++) {
                        var dui = duiArr[j];
                        if (dui.type == 5)
                            break;
                    }
                    if (j == duiArr.length)
                        break;
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    paiArr.push(duiArr[j]['pai_arr'][0]);
                    duiArr.splice(j, 1);
                }

                _.remove(paiArr, function (n) {
                    return n == 0;
                });

                paiArr.sort(function (a, b) {
                    return a - b;
                });
                duiArr.sort(function (a, b) {
                    if (a['pai_arr'][0] == b['pai_arr'][0]) {
                        if (a['pai_arr'][1] == b['pai_arr'][1])
                            return a['pai_arr'][2] - b['pai_arr'][2];
                        return a['pai_arr'][1] - b['pai_arr'][1];
                    }
                    return a['pai_arr'][0] - b['pai_arr'][0];
                });

                var a0 = $('root.panel.row' + i + '.a' + 0);
                //a0.setScale(0.8);
                var anGangCnt = 0;
                var gangCnt = 0;
                for (var j = 0; j < duiArr.length; j++) {
                    var dui = duiArr[j];
                    if (dui.type == 1 || dui.type == 2) {
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][1]);
                        paiIdArr.push(dui['pai_arr'][2]);
                    }
                    if (dui.type == 3) {
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        paiIdArr.push(dui['pai_arr'][0]);
                        gangCnt++;
                    }
                    if (dui.type == 4) {
                        paiIdArr.push(0);
                        paiIdArr.push(0);
                        paiIdArr.push(0);
                        paiIdArr.push(dui['pai_arr'][0]);
                        anGangCnt++;
                    }
                    paiIdArr.push(-1);
                }

                if (anGangCnt)
                    gouchengArr.push('暗杠' + (anGangCnt > 1 ? 'x' + anGangCnt : ''));

                if (gangCnt)
                    gouchengArr.push('明杠' + (gangCnt > 1 ? 'x' + gangCnt : ''));

                if (diangangMap[uid])
                    gouchengArr.push('点杠' + (diangangMap[uid] > 1 ? 'x' + diangangMap[uid] : ''));

                for (var j = 0; j < paiArr.length; j++) {
                    paiIdArr.push(paiArr[j]);
                }

                if (isHu && huPaiId) {
                    if (paiIdArr[paiIdArr.length - 1] != -1)
                        paiIdArr.push(-1);
                    for (var j = 0; j < hupaiMap[uid].length; j++)
                        paiIdArr.push(hupaiMap[uid][j]);

                    gouchengArr.push(isZimo ? '自摸' : '点炮胡');
                }
                else {
                    if (gameData.mapId !== MAP_ID.WANG_DIAO) {
                        //$('root.panel.row' + i + '.lb_fan_text').setVisible(false);
                        //$('root.panel.row' + i + '.lb_score').setVisible(false);
                    }
                }

                if (uid == dianpaoUid) {
                    gouchengArr.push('点炮' + (huCnt > 1 ? 'x' + huCnt : ''));
                }


                if (isHu){
                    if (gameData.options.zhuaMaNum == 100){
                        if (data['other_info']['zhuama_info'] && data['other_info']['zhuama_info']['zhongma_arr'] &&
                            data['other_info']['zhuama_info']['zhongma_arr'][0]) {
                            var zhuamaVal = data['other_info']['zhuama_info']['zhongma_arr'][0];
                            if (zhuamaVal == 32) zhuamaVal = 10;
                            else {
                                zhuamaVal = zhuamaVal % 9;
                                if (zhuamaVal == 0) zhuamaVal = 9;
                            }
                            textArr.push({"中码" : zhuamaVal})
                        }
                    }
                    else if (gameData.options.zhuaMaNum && gameData.options.zhuaMaNum > 0){
                        if (data['other_info']['zhuama_info'] && data['other_info']['zhuama_info']['zhongma_num']) {
                            textArr.push({"中码" : data['other_info']['zhuama_info']['zhongma_num']})
                        }
                        else if (data['other_info']['zhuama_info'] && data['other_info']['zhuama_info']['zhongma_arr']){
                            textArr.push({"中码" : data['other_info']['zhuama_info']['zhongma_arr'].length})
                        }
                    }
                }

                if (textArr) {
                    gouchengArr = [];
                    for (var j = 0; j < textArr.length; j++) {
                        var obj = textArr[j];
                        for (var key in obj)
                            if (key == "中码") {
                                gouchengArr.push(decodeURIComponent(key) + (obj[key]? 'x' + obj[key] : 'x0'));
                            }
                            else if (isHu && decodeURIComponent(key)  == "囤数") {
                                if (obj["中码"]) {
                                    gouchengArr.push(decodeURIComponent(key) + ((obj[key] + obj["中码"]) > 1 ? 'x' + obj[key] : ''));
                                }
                                else {
                                    gouchengArr.push(decodeURIComponent(key) + (obj[key] > 1 ? 'x' + obj[key] : ''));
                                }
                            }
                            else {
                                gouchengArr.push(decodeURIComponent(key) + (obj[key] > 1 ? 'x' + obj[key] : ''));
                            }
                    }
                }

                // gouchengArr.sort(function (a, b) {
                //     return a < b;
                // });
                $('root.panel.row' + i + '.lb_goucheng').setString(gouchengArr.join(' '));

                var gapNum = 0;
                var gapDistance = 20;
                for (var j = 0; j < paiIdArr.length; j++) {
                    if (paiIdArr[j] == -1) {
                        gapNum++;
                        continue;
                    }
                    var pai = $('root.panel.row' + i + '.a' + j);
                    if (!pai) {
                        pai = duplicateNode(a0);
                        pai.setPositionX(a0.getPositionX() + a0.getContentSize().width * 0.97 * a0.getScaleX() * (j - gapNum) + gapNum * gapDistance);
                        a0.getParent().addChild(pai, -1);
                    }

                    var paiName = 'p2s' + paiIdArr[j] + '.png';
                    setSpriteFrameByName(pai, paiName, 'pai');
                    var lb_gui = cc.textureCache.addImage(majiang.res.lb_gui_png);
                    if (gameData.mapId == MAP_ID_LEIYANG || gameData.mapId == MAP_ID_LEIYANGHONGZHONG) {
                        var lb = pai.getChildByName('lb');
                        if (paiIdArr[j] == data['laizi_id']) {
                            grayYellow(pai);
                        } else {
                            recoverColor(pai);
                        }
                    }

                }
            }

            if (data['pqmb']) {
                var pqmbArr = data['pqmb'];
                for (var i = 0; i < pqmbArr.length; i++) {
                    var s = pqmbArr[i];
                    $('root.panel.row' + i + '.lb_pqmb_').setVisible(s != 0);
                    $('root.panel.row' + i + '.lb_pqmb').setVisible(s != 0);
                    $('root.panel.row' + i + '.lb_pqmb').setString(s);
                }
            }

            $('root.panel.lb_ts').setString(timestamp2time(data['ts']));
            $('root.panel.lb_title').setString(title);
            $('root.panel.lb_roomid').setString('房号 ' + gameData.roomId + '      局数 ' + data['cur_round'] + '/' + data['total_round']);

            for (var i = players.length; i < 4; i++)
                $('root.panel.row' + i).setVisible(false);

            TouchUtil.setOnclickListener(btnFenxiang, function () {
                if (!cc.sys.isNative)
                    return;
                ShareUtil.SharePic(that);
            });

            TouchUtil.setOnclickListener(btnStart, function () {
                // ready
                network.send(3004, {room_id: gameData.roomId});
                window.maLayer.onJiesuanClose(true);
                that.removeFromParent(true);
                window.maLayer.zongJiesuan();
            });

            var closeFunc = function () {
                // ready
                window.maLayer.onJiesuanClose(false);
                that.removeFromParent(true);
            };
            TouchUtil.setOnclickListener($('root.panel.btn_close'), closeFunc);
            TouchUtil.setOnclickListener(btnChakan, closeFunc);

            if (data['is_last']) {
                btnStart.setVisible(true);
                btnChakan.setVisible(false);
                //setPosition(cc.winSize.width / 2, btnFenxiang.getPositionY());
            }

            // 抓马显示
            var ma = $('root.panel.ma');
            var children = ma.getChildren();
            idx = 0;
            for (; idx < children.length; idx++) {
                if (children[idx] instanceof cc.Sprite) {
                    safeHide(children[idx]);
                }
            }
            safeHide(ma);
            var zhongma_pai_arr = data['zhongma_pai_arr'] || data['zhongma_arr'] || [];
            if (gameData.mapId === MAP_ID.WANG_DIAO && data['other_info']) {
                var ma_arr = [];
                if (data['other_info']['zhuama_info'] && data['other_info']['zhuama_info']['zhongma_arr'] &&
                    data['other_info']['zhuama_info']['ma_arr']) {
                    zhongma_pai_arr = deepCopy(data['other_info']['zhuama_info']['zhongma_arr'] || []);
                    ma_arr = deepCopy(data['other_info']['zhuama_info']['ma_arr'] || []);
                    if (ma_arr.length > 0){
                        for (var i = 0; i < ma_arr.length; i++) {
                            var pai = $('root.panel.ma.a' + i);
                            var existCardLocation = -1;
                            if (cc.sys.isObjectValid(pai)) {
                                var name = 'p2l' + ma_arr[i] + '.png';
                                setSpriteFrameByName(pai, name, 'pai');
                                existCardLocation = zhongma_pai_arr.indexOf(ma_arr[i]);
                                if (existCardLocation >= 0){
                                    cc.log( ma_arr[i])
                                    zhongma_pai_arr.splice(existCardLocation, 1);
                                    pai.getChildByName("mask").setVisible(false);
                                }
                            }
                            safeShow(pai);
                        }
                        safeShow($('root.panel.ma'));
                        safeShow($('root.panel.ma.lb'));
                    }
                }
            }
            else {
                if (zhongma_pai_arr.length > 0) {
                    for (var i = 0; i < zhongma_pai_arr.length; i++) {
                        var pai = $('root.panel.ma.a' + i);
                        if (cc.sys.isObjectValid(pai)) {
                            var name = 'p2l' + zhongma_pai_arr[i] + '.png';
                            setSpriteFrameByName(pai, name, 'pai');
                            pai.getChildByName("mask").setVisible(true);
                        }
                        safeShow(pai);
                    }
                    safeShow($('root.panel.ma'));
                    safeShow($('root.panel.ma.lb'));
                }
            }

            return true;
        }
    });
})();